from tkinter import *
import tkinter.filedialog as tkxz
from openpyxl import Workbook
from openpyxl.reader.excel import load_workbook
root = Tk()
root.title("工资条生成器")
filenameG = ''
def xz():
    filename = tkxz.askopenfilename(filetypes=[("xlsx", "*.xlsx")])
    if filename!='':
        global filenameG
        filenameG = filename
        v.set(filename)
        Button(root, text='生成工资条', command=gzt, state='normal').grid(row=1, column=1)
    else:
        v.set("您没有选择文件")
        Button(root, text='生成工资条', command=gzt, state='disable').grid(row=1, column=1)
def gzt():
    # print(filenameG)
    excel = load_workbook(filenameG)
    get_names = excel.sheetnames
    print(get_names)
    if "工资条" in get_names:
        # gzt_name = excel.get_sheet_by_name("工资条")
        excel.remove_sheet(excel.get_sheet_by_name("工资条"))
        # gzt_name.SheetName = "旧工资条"
    excel.create_sheet("工资条")
    a_sheet = excel.active
    gzt_sheet = excel.get_sheet_by_name("工资条")
    title = []
    for t_line in a_sheet['1']:
        title.append(t_line.value)
    # print(title)
    max_rows = a_sheet.max_row
    if max_rows <= 1:
        v.set("您选择的表格没有激活工资表sheet")
    else:
        for i in range(2, max_rows):
            append_txt = []
            gzt_sheet.append(title)
            for ii in a_sheet['%d' % i]:
                append_txt.append(ii.value)
            gzt_sheet.append(append_txt)
        excel.save(filenameG)
        v.set("修改成功！")
        Button(root, text='生成工资条', command=gzt, state='disable').grid(row=1, column=1)

v = StringVar()
v.set("请确保excel表格中没有\"工资条\"标签")
path = Entry(root,textvariable=v,width=30).grid(row=0,column=0, columnspan=3)
btn1 = Button(root,text='选择文件',command=xz).grid(row=1,column=0)
btn2 = Button(root,text='生成工资条',command=gzt,state='disable').grid(row=1,column=1)
btn3 = Button(root,text='退出',command=root.quit).grid(row=1,column=2)
root.mainloop()